#!/usr/bin/python3

import os

IsFile = os.path.isfile('screenres.py')
if IsFile:
    pass
else:  # Set Window Width and Height 900x500
    print('No Resolution File detected.')
    print('Please enter your screen width (ex. 1920, 900): ')
    wdth = input()
    print('Please enter your screen height (ex. 1080, 500): ')
    hght = input()
    f = open("screenres.py", "x")
    f.write("WIDTH, HEIGHT = " + wdth + "," + hght)
    print('Sucessfully created resolution file. Please re-open the game.')
    quit()

import pygame
from pygame import mixer
from screenres import *
from config import *


HEISENBERG = pygame.image.load('assets/element.jpg')  # Load player images
SCHRADER = pygame.image.load('assets/element2.jpg')
BACKGRND = pygame.transform.scale(pygame.image.load("assets/back32.jpg"), (WIDTH, HEIGHT))


class Main:
    def __init__(self):
        pygame.font.init()
        pygame.init()

        pygame.display.set_caption("heisenberg simulator")  # Set Window Caption

        self.init_audio()

        self.window = pygame.display.set_mode((WIDTH, HEIGHT))
        self.mid_border = pygame.Rect(WIDTH // 2 - 5, 0, 5, HEIGHT)  # create border down the middle

        self.winner_font = pygame.font.SysFont('comicsans', 90)
        self.health_font = pygame.font.SysFont('source code pro', 40)

        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.yellow = (255, 255, 0)

        self.schrader_hit = pygame.USEREVENT + 1
        self.heisenberg_hit = pygame.USEREVENT + 2

        self.clock = pygame.time.Clock()

        self.schrader_rect = pygame.Rect(HEIGHT / 2, WIDTH / 4, 100, 125)  # left-wasd
        self.heisenberg_rect = pygame.Rect(HEIGHT, WIDTH / 4, 100, 125)  # right-arrow

        self.schrader_bullets = []
        self.heisenberg_bullets = []

        self.schrader_health = 10
        self.heisenberg_health = 10

    def init_audio(self):
        mixer.pre_init()
        mixer.init()

        mixer.Channel(0).play(mixer.Sound('assets/Better Call Saul Main Title Theme (Extended).mp3'))
        mixer.Channel(1).play(mixer.Sound('assets/Breaking Bad Main Title Theme (Extended).mp3'))

        mixer.Channel(0).set_volume(0.1)
        mixer.Channel(1).set_volume(0.4)
        mixer.Channel(2).set_volume(5)
        mixer.Channel(3).set_volume(5)

        mixer.set_num_channels(5)

    def draw_window(self, schrader_rect, heisenberg_rect, schrader_bullets, heisenberg_bullets, schrader_health, heisenberg_health):
        self.window.blit(BACKGRND, (0, 0))  # Make sure to fill the screen BEFORE adding the players
        pygame.draw.rect(self.window, self.white, self.mid_border)

        self.window.blit(HEISENBERG, (heisenberg_rect.x, heisenberg_rect.y))  # define player locations
        self.window.blit(SCHRADER, (schrader_rect.x, schrader_rect.y))

        schrader_health_text = self.health_font.render("HEALTH: " + str(heisenberg_health), 1, self.white)
        heisenberg_health_text = self.health_font.render("HEALTH: " + str(schrader_health), 1, self.white)

        self.window.blit(heisenberg_health_text, (WIDTH - schrader_health_text.get_width() - HEIGHT // 22, WIDTH // 102))
        self.window.blit(schrader_health_text, (HEIGHT // 22, WIDTH // 102))

        for bullet in schrader_bullets:
            pygame.draw.rect(self.window, self.yellow, bullet)

        for bullet in heisenberg_bullets:
            pygame.draw.rect(self.window, self.yellow, bullet)

        pygame.display.update()  # update the display

    def handle_bullets(self, schrader_bullets, heisenberg_bullets, schrader_rect, heisenberg_rect):
        for bullet in schrader_bullets:
            bullet.x += BULLETS_VEL
            if heisenberg_rect.colliderect(bullet):
                pygame.event.post(pygame.event.Event(self.heisenberg_hit))
                schrader_bullets.remove(bullet)
            elif bullet.x > WIDTH:
                schrader_bullets.remove(bullet)

        for bullet in heisenberg_bullets:
            bullet.x -= BULLETS_VEL
            if schrader_rect.colliderect(bullet):
                pygame.event.post(pygame.event.Event(self.schrader_hit))
                heisenberg_bullets.remove(bullet)
            elif bullet.x < 0:
                heisenberg_bullets.remove(bullet)

    def draw_winner(self, text):
        draw_text = self.winner_font.render(text, 1, self.black)
        self.window.blit(draw_text, (WIDTH / 2 - draw_text.get_width() / 2, HEIGHT / 2 - draw_text.get_height() / 2))
        pygame.display.update()
        pygame.time.delay(3000)

    def loop(self):
        while True:
            self.clock.tick(60)  # set the FPS

            for event in pygame.event.get():  # wait for quit event
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit(0)

                if event.type == pygame.KEYDOWN:
                    if event.key == getattr(pygame, f"K_{ASAC_SCHRADER_SHOOT}") and len(self.schrader_bullets) < MAX_BULLETS:
                        bullet = pygame.Rect(self.schrader_rect.x + self.schrader_rect.width, self.schrader_rect.y + self.schrader_rect.height // 2 - 2, 50, 5)
                        self.schrader_bullets.append(bullet)
                    if event.key == getattr(pygame, f"K_{HEISENBERG_SHOOT}") and len(self.heisenberg_bullets) < MAX_BULLETS:
                        bullet = pygame.Rect(self.heisenberg_rect.x, self.heisenberg_rect.y + self.heisenberg_rect.height // 2 - 2, 50, 5)
                        self.heisenberg_bullets.append(bullet)

                if event.type == self.heisenberg_hit:
                    # print('self.heisenberg_rect_HIT')
                    self.schrader_health += 1
                    self.heisenberg_health -= 1
                    mixer.Channel(2).play(mixer.Sound('assets/hankde.mp3'))

                if event.type == self.schrader_hit:
                    # print('self.schrader_HIT')
                    self.heisenberg_health += 1
                    mixer.Channel(3).play(mixer.Sound('assets/say_myname.mp3'))
                    self.schrader_health -= 1

            if self.schrader_health > 15:
                self.schrader_health = 15

            if self.heisenberg_health > 15:
                self.heisenberg_health = 15

            winner_text = ""
            if self.heisenberg_health <= 0:
                winner_text = "ASAC Schrader Wins!"
            if self.schrader_health <= 0:
                winner_text = "Heisenberg Wins!"

            if winner_text != "":
                self.draw_winner(winner_text)
                break

            keys_pressed = pygame.key.get_pressed()
            if keys_pressed[getattr(pygame, f"K_{ASAC_SCHRADER_LEFT}")] and self.schrader_rect.x - VEL > 0:  # left
                self.schrader_rect.x -= VEL
            elif keys_pressed[getattr(pygame, f"K_{ASAC_SCHRADER_RIGHT}")] and self.schrader_rect.x + VEL + self.schrader_rect.width < self.mid_border.x:  # right
                self.schrader_rect.x += VEL
            elif keys_pressed[getattr(pygame, f"K_{ASAC_SCHRADER_UP}")] and self.schrader_rect.y - VEL > 0:  # up
                self.schrader_rect.y -= VEL
            elif keys_pressed[getattr(pygame, f"K_{ASAC_SCHRADER_DOWN}")] and self.schrader_rect.y + VEL + self.schrader_rect.height < HEIGHT:  # down
                self.schrader_rect.y += VEL

            if keys_pressed[getattr(pygame, f"K_{HEISENBERG_LEFT}")] and self.heisenberg_rect.x - VEL > self.mid_border.x + self.mid_border.width - 5:  # left
                self.heisenberg_rect.x -= VEL
            elif keys_pressed[getattr(pygame, f"K_{HEISENBERG_RIGHT}")] and self.heisenberg_rect.x + VEL + self.heisenberg_rect.width < WIDTH:  # right
                self.heisenberg_rect.x += VEL
            elif keys_pressed[getattr(pygame, f"K_{HEISENBERG_UP}")] and self.heisenberg_rect.y - VEL > 0:  # up
                self.heisenberg_rect.y -= VEL
            elif keys_pressed[getattr(pygame, f"K_{HEISENBERG_DOWN}")] and self.heisenberg_rect.y + VEL + self.heisenberg_rect.height < HEIGHT:  # down
                self.heisenberg_rect.y += VEL

            self.handle_bullets(self.schrader_bullets, self.heisenberg_bullets, self.schrader_rect, self.heisenberg_rect)

            self.draw_window(self.schrader_rect, self.heisenberg_rect, self.schrader_bullets, self.heisenberg_bullets, self.heisenberg_health, self.schrader_health)

    def run(self):
        self.loop()


if __name__ == "__main__":
    game = Main()
    game.run()
